/**
 * Translate.java
 * Copyright (C) 2007, Richard Midwinter
 * This file is part of google-api-translate-java.
 * google-api-translate-java is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * google-api-translate-java is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
 */
package com.google.api.translate;

import java.net.URL;
import java.net.URLEncoder;

import main.Main;

import org.json.JSONObject;

import tools.StringTools;

import com.google.api.GoogleAPI;

/**
 * Makes the Google Translate API available to Java applications.
 * 
 * @author Richard Midwinter
 * @author Mike Nereson
 * @author Emeric Vernat
 * @author Juan B Cabral
 * @author Kramar Tomas
 */
public final class Translate extends GoogleAPI {

   /**
    * Constants.
    */
   private static final String URL = "https://www.googleapis.com/language/translate/v2?",
		 PARAMETERS = "key=#KEY#&format=text&prettyprint=true&source=#FROM#&target=#TO#&q=",
		 DETECT_PARAMETERS = "key=#KEY#&format=text&prettyprint=true&target=#TO#&q=";

   /**
    * Translates text from a given Language to another given Language using Google Translate.
    * 
    * @param text
    *           The String to translate.
    * @param from
    *           The language code to translate from.
    * @param to
    *           The language code to translate to.
    * @return The translated String.
    * @throws Exception
    *            on error.
    */
   public static String execute(final String text, final String from, final String to) throws Exception {
	  validateReferrer();
	  if (StringTools.isNullOrEmpty(Main.getBotSettings().getGoogleAPIKey()))
		 throw new Exception("Google API key is missing");

	  String parameters = "".equals(from) ? DETECT_PARAMETERS : PARAMETERS;
	  parameters = parameters.replaceAll("#FROM#", from).replaceAll("#TO#", to)
			.replaceAll("#KEY#", Main.getBotSettings().getGoogleAPIKey())
			+ URLEncoder.encode(text, ENCODING);
	  final URL url = new URL(URL + parameters);

	  final JSONObject json = retrieveJSON(url);
	  if (json == null)
		 throw new NullPointerException();
	  return getJSONResponse(json);
   }

   /**
    * Returns the JSON response data as a String. Throws an exception if the status is not a 200 OK.
    * 
    * @param json
    *           The JSON object to retrieve the response data from.
    * @return The responseData from the JSONObject.
    * @throws Exception
    *            If the responseStatus is not 200 OK.
    */
   private static String getJSONResponse(final JSONObject json) throws Exception {
	  return json.getJSONObject("data").getJSONArray("translations").getJSONObject(0).getString("translatedText");
   }
}